package czy.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;


/**
 * 三级概念
 * 索引:相当于数据库,框架不会自动创建
 * 类型:相当于表,一个类型与一个类为一个映射,映射关系会自动添加
 * 文档:我们操作的就是文档
 * 映射:代表了POJO对象属性的字段映射,如
 * "properties": {
 *               "age": {
 *                   "type": "long"
 *               },
 *               "create": {
 *                  "type": "long"
 *               },
 *               "id": {
 *                   "type": "text",
 *                   "fields": {
 *                       "keyword": {
 *                           "type": "keyword",
 *                           "ignore_above": 256
 *                       }
 *                   }
 *               },
 *              "name": {
 *                   "type": "text",
 *                  "fields": {
 *                       "keyword": {
 *                           "type": "keyword",
 *                           "ignore_above": 256
 *                       }
 *                   }
 *               }
 *           }
 *       }
 */
@Configuration
@EnableElasticsearchRepositories
public class SpringElasticSearchConfig implements InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(SpringElasticSearchConfig.class);

    @Value("${elasticsearch.index-name}")
    private String indexName;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 索引不会自动创建,如果不存在,会抛出异常
     */
    @Override
    public void afterPropertiesSet(){
        if(!this.elasticsearchTemplate.indexExists(indexName)){
            logger.info("索引不存在，创建新的索引");
            this.elasticsearchTemplate.createIndex(indexName);
        }
    }
}
